/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.handler;

import cn.ac.iie.di.ban.dao.MySQLDao;
import cn.ac.iie.di.ban.tools.MySQLHelper;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import net.sf.json.JSONObject;

/**
 *
 * @author xiaoliang
 */
public class SE2DBWorkerMysqlCommon extends SE2DBWorker {

    private static org.apache.log4j.Logger logger = Logger.getLogger(SE2DBWorkerMysqlCommon.class.getName());
    private MySQLHelper mySQLHelper;
    private MySQLDao mySQLDao;
    private Map<String, Object> contentMsg = new HashMap<>(6);

    public SE2DBWorkerMysqlCommon(HttpSe2DBHandler httpSe2DBHandler, String pDWType) {
        super(httpSe2DBHandler, pDWType);
    }

    @Override
    public void init() throws Exception {
        mySQLHelper = MySQLHelper.getMySQLHelper(
                HttpSe2DBHandler.getDriver(),
                HttpSe2DBHandler.getUrl(),
                HttpSe2DBHandler.getUser(),
                HttpSe2DBHandler.getPwd(),
                HttpSe2DBHandler.getInitSize(),
                HttpSe2DBHandler.getMaxSize());
        mySQLDao = new MySQLDao(mySQLHelper, load2DBEntity);
        mySQLDao.init();
        mySQLDao.getDBCols();
    }

    @Override
    public void loadData0() {
        String rflag = "";
        try {
            start_time = System.currentTimeMillis();
            List<Map<String, Object>> docRecords = new ArrayList();
            for (Map<String, Object> record : docRecordSet) {
                record.put("it", System.currentTimeMillis() / 1000);
                docRecords.add(record);
            }
            int[] result = mySQLDao.saveRecord(docRecords);
            int insertcount = 0;
            for (int i = 0; i < result.length; i++) {
                if (result[i] == 1) {
                    insertcount++;
                } else {
                     logger.error("insert error msg : "+docRecords.get(i));
                }
            }
            end_time = System.currentTimeMillis();
            logger.info("save " + docRecordSet.size() + "|expect " + insertcount + " record to " + httpSe2DBHandler.getTable() + " successfully " + " using " + (end_time - start_time) + " ms ");
            docRecordSet.clear();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    @Override
    public void freeSource() {
        mySQLHelper.close(mySQLDao.getConn());
    }
}
